package com.xtecher.app.column.ui;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.google.gson.Gson;
import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.xtecher.app.Config;
import com.xtecher.app.R;
import com.xtecher.app.base.BaseActivity;
import com.xtecher.app.base.BaseApplication;
import com.xtecher.app.column.ColumnContact;
import com.xtecher.app.column.ColumnPresenter;
import com.xtecher.app.column.bean.ColumnDetailResponse;
import com.xtecher.app.user.FollowUtils;
import com.xtecher.app.utils.AccessTokenKeeper;
import com.xtecher.app.utils.Util;
import com.xtecher.app.widget.HeadZoomScrollView;

import java.util.concurrent.ExecutionException;

public class ColumnDetailActivity extends BaseActivity implements ColumnContact.View, IWeiboHandler.Response {

    private ColumnPresenter mPresenter;
    private HeadZoomScrollView scrollView;
    private ImageView imgTop;
    private TextView tvTitle;
    private TextView tvName;
    private TextView tvDate;
    private TextView tvFrom;
    private TextView tvCopy;
    private TextView tvContent;
    private ImageView imgAvatar;
    private WebView webView;
    private RelativeLayout reBottom;
    private ImageView imgBack;
    private ImageView imgShare;
    private View divider;
    private FrameLayout fmFollow;
    private TextView tvFollow;
    private ImageView imgFollow;
    private View view;
    private String uid;
    private boolean isFollow = false;
    private FrameLayout frameLayout;
    private ColumnDetailResponse.ShareBean share;
    private IWeiboShareAPI mWeiboShareAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
        setContentView(R.layout.activity_column_detail);
        initView();
        initListener();
        mPresenter = new ColumnPresenter(this);
        long aid = getIntent().getLongExtra("aid", 0);
        mPresenter.getArticle("?aid=" + aid);
        // 创建微博分享接口实例
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Config.APP_KEY);

        // 注册第三方应用到微博客户端中，注册成功后该应用将显示在微博的应用列表中。
        // 但该附件栏集成分享权限需要合作申请，详情请查看 Demo 提示
        // NOTE：请务必提前注册，即界面初始化的时候或是应用程序初始化时，进行注册
        mWeiboShareAPI.registerApp();

        // 当 Activity 被重新初始化时（该 Activity 处于后台时，可能会由于内存不足被杀掉了），
        // 需要调用 {@link IWeiboShareAPI#handleWeiboResponse} 来接收微博客户端返回的数据。
        // 执行成功，返回 true，并调用 {@link IWeiboHandler.Response#onResponse}；
        // 失败返回 false，不调用上述回调
        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }

    }

    private void initListener() {
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        imgShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        fmFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFollow) {
                    if (FollowUtils.clearFollow(ColumnDetailActivity.this, uid)) {
                        isFollow = false;
                        imgFollow.setVisibility(View.GONE);
                        tvFollow.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (FollowUtils.addFollow(ColumnDetailActivity.this, uid)) {
                        isFollow = true;
                        imgFollow.setVisibility(View.VISIBLE);
                        tvFollow.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initView() {
        frameLayout = (FrameLayout) findViewById(R.id.frame);
        scrollView = (HeadZoomScrollView) findViewById(R.id.scrollView);
        imgTop = (ImageView) findViewById(R.id.img_top);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvDate = (TextView) findViewById(R.id.tv_date);
        tvFrom = (TextView) findViewById(R.id.tv_from);
        tvCopy = (TextView) findViewById(R.id.tv_copy);
        fmFollow = (FrameLayout) findViewById(R.id.fm_follow);
        tvFollow = (TextView) findViewById(R.id.tv_follow);
        imgFollow = (ImageView) findViewById(R.id.img_follow);
        scrollView.setZoomView(null);
        view = findViewById(R.id.view);
        tvContent = (TextView) findViewById(R.id.tv_content);
        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        webView = (WebView) findViewById(R.id.webview);
        reBottom = (RelativeLayout) findViewById(R.id.re_bottom);
        imgBack = (ImageView) findViewById(R.id.img_back);
        imgShare = (ImageView) findViewById(R.id.img_share);
        divider = findViewById(R.id.view_divider);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return true;
            }
        });

        scrollView.setOnScrollListener((scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY - oldScrollY > 20) { //上滑
                reBottom.setBackgroundResource(R.color.transparent);
                imgBack.setVisibility(View.GONE);
                imgShare.setVisibility(View.GONE);
                divider.setVisibility(View.GONE);
            } else if (scrollY - oldScrollY < -20) { //下滑
                reBottom.setBackgroundResource(R.color.white);
                imgBack.setVisibility(View.VISIBLE);
                imgShare.setVisibility(View.VISIBLE);
                divider.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void setData(Object o, @Nullable int id) {
        switch (id) {
            case 0:
                ColumnDetailResponse detailResponse = new Gson().fromJson((String) o, ColumnDetailResponse.class);
                share = detailResponse.getShare();
                uid = detailResponse.getAuthor().getUid();
                initData(detailResponse);
                break;
        }
    }

    private void initData(ColumnDetailResponse response) {
        isFollow = FollowUtils.isFollow(this, uid);
        if (isFollow) {
            imgFollow.setVisibility(View.VISIBLE);
            tvFollow.setVisibility(View.GONE);
        } else {
            imgFollow.setVisibility(View.GONE);
            tvFollow.setVisibility(View.VISIBLE);
        }
        Glide.with(this)
                .load(response.getCover_pic())
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .placeholder(R.drawable.content_cover)
                .error(R.drawable.content_cover)
                .into(imgTop);

        Glide.with(this)
                .load(response.getAuthor().getAvatar())
                .asBitmap()
                .centerCrop()
                .placeholder(R.drawable.detail_avatar_2)
                .error(R.drawable.detail_avatar_2)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(new BitmapImageViewTarget(imgAvatar) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        imgAvatar.setImageDrawable(circularBitmapDrawable);
                    }
                });
        tvTitle.setText(response.getTitle());
        tvName.setText(response.getAuthor().getName());
        tvFrom.setText(String.format("来源: %s", response.getSource()));
        tvCopy.setText(String.format("版权信息: %s", response.getCopyright()));
        String[] split = response.getCreate_date().split(" ");
        if (split != null)
            tvDate.setText(String.format("时间: %s", split[0]));
//        tvContent.setText(Html.fromHtml(response.getContent(), new URLImageParser(tvContent), null));
        webView.loadUrl(response.getContent_url());

    }

    private void showShare() {
        if (share == null)
            return;
        PopupWindow popupWindow = new PopupWindow(this);
        View view = View.inflate(this, R.layout.pop_share, null);
        LinearLayout linWx = (LinearLayout) view.findViewById(R.id.lin_wx);
        LinearLayout linWxc = (LinearLayout) view.findViewById(R.id.lin_wxc);
        LinearLayout linWb = (LinearLayout) view.findViewById(R.id.lin_wb);
        linWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = share.getUrl();
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = share.getTitle();
                msg.description = share.getDescr();

                try {
                    Bitmap bitmap = Glide.with(ColumnDetailActivity.this)
                            .load(share.getImage())
                            .asBitmap()
                            .into(120, 120)
                            .get();
                    msg.thumbData = Util.bmpToByteArray(bitmap, true);
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;
                BaseApplication.wxapi.sendReq(req);
                popupWindow.dismiss();
            }
        });
        linWxc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = share.getUrl();
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = share.getTitle();
                msg.description = share.getDescr();
                try {
                    Bitmap bitmap = Glide.with(ColumnDetailActivity.this)
                            .load(share.getImage())
                            .asBitmap()
                            .into(120, 120)
                            .get();
                    msg.thumbData = Util.bmpToByteArray(bitmap, true);
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                BaseApplication.wxapi.sendReq(req);
                popupWindow.dismiss();

            }
        });
        linWb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMultiMessage(share);
                popupWindow.dismiss();

            }
        });
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(view);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(frameLayout, Gravity.BOTTOM, 0, reBottom.getHeight());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    /**
     * 新浪微博分享
     *
     * @param share
     */
    private void sendMultiMessage(ColumnDetailResponse.ShareBean share) {
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.mediaObject = getWebpageObj(share);
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, Config.APP_KEY, Config.REDIRECT_URL, Config.SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
        }
        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {

            @Override
            public void onWeiboException(WeiboException arg0) {
            }

            @Override
            public void onComplete(Bundle bundle) {
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
            }

            @Override
            public void onCancel() {
            }
        });

    }

    private BaseMediaObject getWebpageObj(ColumnDetailResponse.ShareBean share) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = share.getTitle();
        mediaObject.description = share.getDescr();
        try {
            Bitmap bitmap = Glide.with(ColumnDetailActivity.this)
                    .load(share.getImage())
                    .asBitmap()
                    .into(120, 120)
                    .get();
            mediaObject.setThumbImage(bitmap);

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        mediaObject.actionUrl = share.getUrl();
        mediaObject.defaultText = "填写分享内容";
        return mediaObject;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    public void onResponse(BaseResponse baseResp) {
        if (baseResp != null) {
            switch (baseResp.errCode) {
                case WBConstants.ErrorCode.ERR_OK:
                    showMessage("分享成功");
                    break;
                case WBConstants.ErrorCode.ERR_CANCEL:
                    showMessage("分享取消");
                    break;
                case WBConstants.ErrorCode.ERR_FAIL:
                    showMessage("分享失败");
                    break;
            }
        }

    }
}
